/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-07 09:26:03
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-16 09:07:42
 * @FilePath: /yt-devops/lib/components/network_image_load/image_utils.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

String imageUrlPath = '';

class ImageUtils {
  //必须先初始化,不然拿不到图片主地址路径
  static void initialization(String imageBasePath) {
    imageUrlPath = imageBasePath;
  }

  static ImageProvider getAssetImage(String name, {String format = 'png'}) {
    return AssetImage(getImgPath(name, format: format));
  }

  static String getImgPath(String name, {String? format = 'png'}) {
    return '$name.$format';
  }

  static String getNetworkImgPath(String imageUrl) {
    if (!imageUrl.startsWith('http') && !imageUrl.startsWith('https')) {
      imageUrl = AppImagePath(imageUrl);
    }
    return imageUrl;
  }

  static ImageProvider getImageProvider(String imageUrl,
      {String holderImg = 'none'}) {
    if (imageUrl == '') {
      return AssetImage(getImgPath(holderImg));
    }

    if (imageUrl.startsWith('file:') || imageUrl.startsWith('assets')) {
      return AssetImage(imageUrl);
    }
    return CachedNetworkImageProvider(AppImagePath(imageUrl));
  }

  // 获取网络图片完全地址
  // ignore: non_constant_identifier_names
  static String AppImagePath(String path) {
    String imageURL = imageUrlPath;
    RegExp url = RegExp("^((https|http)?://)[^s]+");
    if (path.isEmpty || path == '' || imageURL.isEmpty || imageURL == '') {
      return '';
    } else if ((path != '' && path!.isNotEmpty) && url.hasMatch(path)) {
      return path;
    } else {
      bool hasSuffix = (imageURL.substring(imageURL.length - 1) == '/');
      bool hasPrefix = (path.substring(0, 1) == '/');

      if (hasPrefix && hasSuffix) {
        return imageURL + path.substring(1);
      } else if (!hasPrefix && !hasSuffix) {
        return '$imageURL/$path';
      }
      return imageURL + path;
    }
  }
}
